<?php
declare (strict_types=1);

namespace app\controller\admin;

use app\util\ReturnCode;
use app\model\RailwayStation as RailwayStationModel;
use app\model\CheckItem as CheckItemModel;
use app\model\CheckRecord as CheckRecordModel;
class CheckRecord extends Base
{
    public function lists()
    {
        $where = [];
        $status = $this->request->get('status', '');
        $keywords = $this->request->get('keywords', '');
        $page = $this->request->get('page', 1, 'intval');
        $size = $this->request->get('size', 10, 'intval');
        
        if($status !== '') {
            $where[] = ['ci.status', '=', $status];
        }
        if($keywords) {
            $where[] = ['r.name', 'like', '%'.$keywords.'%'];
        }

        $railway_stations = RailwayStationModel::column('name', 'id');
        $list = CheckItemModel::alias('ci')
            ->join('check_record cr', 'cr.id=ci.check_record_id')
            ->join('railway r', 'r.id=cr.railway_id')
            ->join('user u', 'u.id=ci.user_id')
            ->where($where)
            ->field('ci.*, r.name as railway_name, u.name as user_name')
            ->order('ci.id', 'desc')
            ->paginate($size);

        $list = $list->each(function($item) use ($railway_stations) {
            // 格式化时间
            $timeFields = ['create_time', 'station_time', 'boarding_time', 'departure_time', 'arrival_time', 'complete_time'];
            foreach($timeFields as $field) {
                if(isset($item[$field]) && $item[$field] > 0) {
                    $item[$field] = date('Y-m-d H:i:s', intval($item[$field]));
                } else {
                    $item[$field] = '';
                }
            }
            $item['station_name'] = $railway_stations[$item['arrival_id']] ?? '';
            if ($item['type'] === 1) {
                $item['direction_text'] = $item['direction'] === 1 ? '上行' : '下行';
            }
            $item['start_text'] = $railway_stations[$item['start_id']] ?? '';
            $item['end_text'] = $railway_stations[$item['end_id']] ?? '';
            return $item;
        });
            
        $data = [
            'count' => $list->total(),
            'list' => $list->items()
        ];
        return $this->buildSuccess($data);
    }

    public function recordInfo()
    {
        $id = $this->request->get('id', 0);
        if (!$id) {
            return $this->buildFailed(ReturnCode::INVALID, '参数错误');
        }

        $data = CheckItemModel::alias('ci')
            ->join('check_record cr', 'cr.id=ci.check_record_id')
            ->join('railway r', 'r.id=cr.railway_id', 'left')
            ->join('railway_station rs', 'rs.id=ci.arrival_id', 'left')
            ->join('user u', 'u.id=ci.user_id', 'left')
            ->where([
                ['ci.id', '=', $id],
                ['ci.delete_time', '=', null]
            ])
            ->field('ci.*, r.name as railway_name, rs.name as station_name, u.name as user_name')
            ->find();

        if (!$data) {
            return $this->buildFailed(ReturnCode::INVALID, '未找到相关记录');
        }

        $data = $data->toArray();

        // 获取车站名称映射
        $railway_stations = RailwayStationModel::column('name', 'id');

        // 格式化时间
        $timeFields = ['create_time', 'update_time', 'delete_time', 'station_time', 'boarding_time', 'departure_time', 'arrival_time', 'complete_time'];
        foreach ($timeFields as $field) {
            if (isset($data[$field]) && $data[$field] > 0) {
                $data[$field] = date('Y-m-d H:i:s', intval($data[$field]));
            } else {
                $data[$field] = '';
            }
        }

        // 处理图片数组
        if (!empty($data['images_url'])) {
            $data['images_url'] = explode(',', $data['images_url']);
        } else {
            $data['images_url'] = [];
        }

        // 添加车站名称
        $data['station_name'] = $railway_stations[$data['arrival_id']] ?? '';
        $data['start_text'] = $railway_stations[$data['start_id']] ?? '';
        $data['end_text'] = $railway_stations[$data['end_id']] ?? '';

        // 添加方向文本
        if ($data['type'] === 1) {
            $data['direction_text'] = $data['direction'] === 1 ? '上行' : '下行';
        } else {
            $data['direction_text'] = '';
        }

        return $this->buildSuccess($data);
    }

    public function add()
    {
        // 新增检查记录的逻辑
        return $this->buildSuccess();
    }

    public function edit()
    {
        // 编辑检查记录的逻辑
        return $this->buildSuccess();
    }

    public function del()
    {
        $id = $this->request->post('id', 0);
        if(!$id) {
            return $this->buildFailed(ReturnCode::INVALID, '参数错误');
        }
        
        $result = CheckRecordModel::where('id', $id)->update([
            'delete_time' => time()
        ]);
        
        if($result === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }
        
        return $this->buildSuccess();
    }

    public function changeStatus()
    {
        $id = $this->request->get('id');
        $status = $this->request->get('status');
        
        if(!$id || !isset($status)) {
            return $this->buildFailed(ReturnCode::INVALID, '参数错误');
        }
        
        $result = CheckRecordModel::where('id', $id)->update([
            'status' => $status,
            'update_time' => time()
        ]);
        
        if($result === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }
        
        return $this->buildSuccess();
    }
}
